import { Image } from 'expo-image';
import { useLocalSearchParams, useRouter } from 'expo-router';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import {
    ActivityIndicator,
    Dimensions,
    ImageBackground,
    ScrollView,
    StatusBar,
    StyleSheet,
    Text,
    TouchableOpacity,
    View
} from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';

import { CheckoutModal } from '@/components/product/CheckoutModal';
import { Images } from '@/constants/images';
import { getGoodsDetail, GoodsDetail, previewSubmit } from '@/services/mall';

const { width: SCREEN_WIDTH } = Dimensions.get('window');

export default function ProductDetailScreen() {
  const { id, subjectId } = useLocalSearchParams<{ id: string; subjectId?: string }>();
  const router = useRouter();
  const insets = useSafeAreaInsets();
  const checkoutRef = useRef<any>(null);

  const [loading, setLoading] = useState(true);
  const [data, setData] = useState<GoodsDetail | null>(null);

  // 加载商品详情
  const loadData = useCallback(async () => {
    if (!id) return;
    setLoading(true);
    try {
      const detail = await getGoodsDetail(id, subjectId);
      setData(detail);
    } catch (error) {
      console.error('加载商品详情失败:', error);
    }
    setLoading(false);
  }, [id, subjectId]);

  useEffect(() => {
    loadData();
  }, [loadData]);

  // 显示结算弹窗
  const showCheckout = async () => {
    if (!data) return;
    try {
      const preview = await previewSubmit({
        goodsId: id!,
        quantity: 1,
        subjectId,
      });
      if (preview) {
        checkoutRef.current?.show(preview);
      }
    } catch (error) {
      console.error('预提交失败:', error);
    }
  };

  // 返回
  const goBack = () => {
    router.back();
  };

  if (loading) {
    return (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size="large" color="#fff" />
      </View>
    );
  }

  if (!data) {
    return (
      <View style={styles.loadingContainer}>
        <Text style={styles.errorText}>商品不存在</Text>
      </View>
    );
  }

  return (
    <View style={styles.container}>
      <StatusBar barStyle="light-content" />
      <ImageBackground
        source={{ uri: Images.mine.kaixinMineBg }}
        style={styles.background}
        resizeMode="cover"
      >
        {/* 顶部导航 */}
        <View style={[styles.header, { paddingTop: insets.top }]}>
          <TouchableOpacity style={styles.backBtn} onPress={goBack}>
            <Text style={styles.backText}>←</Text>
          </TouchableOpacity>
          <Text style={styles.headerTitle}>商品详情</Text>
          <View style={styles.placeholder} />
        </View>

        <ScrollView style={styles.scrollView} showsVerticalScrollIndicator={false}>
          {/* 商品图片 */}
          <View style={styles.imageWrapper}>
            <Image source={data.spu.cover} style={styles.coverImage} contentFit="cover" />
          </View>

          {/* 商品信息 */}
          <ImageBackground
            source={{ uri: Images.common.itemBg }}
            style={styles.infoSection}
            resizeMode="stretch"
          >
            <View style={styles.priceRow}>
              <Text style={styles.currency}>¥</Text>
              <Text style={styles.price}>{data.subjectPrice || data.price}</Text>
              {data.sellType === 2 && (
                <View style={styles.presellTag}>
                  <Text style={styles.presellText}>预售</Text>
                </View>
              )}
            </View>
            <Text style={styles.name}>{data.spu.name}</Text>
          </ImageBackground>

          {/* 商品详情图片 */}
          {data.spu.images && data.spu.images.length > 0 && (
            <ImageBackground
              source={{ uri: Images.common.itemBg }}
              style={styles.detailSection}
              resizeMode="stretch"
            >
              <Text style={styles.sectionTitle}>商品详情</Text>
              {data.spu.images.map((img, index) => (
                <Image key={index} source={img} style={styles.detailImage} contentFit="contain" />
              ))}
            </ImageBackground>
          )}

          {/* 推荐商品 */}
          {data.recommendedMallGoods && data.recommendedMallGoods.length > 0 && (
            <ImageBackground
              source={{ uri: Images.common.itemBg }}
              style={styles.recommendSection}
              resizeMode="stretch"
            >
              <Text style={styles.sectionTitle}>推荐商品</Text>
              <ScrollView horizontal showsHorizontalScrollIndicator={false}>
                {data.recommendedMallGoods.map((item) => (
                  <TouchableOpacity
                    key={item.id}
                    style={styles.recommendItem}
                    onPress={() => router.push(`/product/${item.id}` as any)}
                  >
                    <Image source={item.cover} style={styles.recommendImage} contentFit="cover" />
                    <Text style={styles.recommendName} numberOfLines={1}>{item.name}</Text>
                    <Text style={styles.recommendPrice}>¥{item.price}</Text>
                  </TouchableOpacity>
                ))}
              </ScrollView>
            </ImageBackground>
          )}

          <View style={styles.bottomSpace} />
        </ScrollView>

        {/* 底部购买栏 */}
        <View style={[styles.bottomBar, { paddingBottom: insets.bottom + 10 }]}>
          <TouchableOpacity style={styles.serviceBtn}>
            <Text style={styles.serviceBtnText}>客服</Text>
          </TouchableOpacity>
          <TouchableOpacity style={styles.buyBtn} onPress={showCheckout} activeOpacity={0.8}>
            <ImageBackground
              source={{ uri: Images.common.loginBtn }}
              style={styles.buyBtnBg}
              resizeMode="stretch"
            >
              <Text style={styles.buyBtnText}>
                {data.sellType === 2 ? '支付定金' : '立即购买'}
              </Text>
            </ImageBackground>
          </TouchableOpacity>
        </View>
      </ImageBackground>

      {/* 结算弹窗 */}
      <CheckoutModal
        ref={checkoutRef}
        data={data}
        goodsId={id!}
        subjectId={subjectId}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#1a1a2e',
  },
  background: {
    flex: 1,
  },
  loadingContainer: {
    flex: 1,
    backgroundColor: '#1a1a2e',
    justifyContent: 'center',
    alignItems: 'center',
  },
  errorText: {
    color: '#999',
    fontSize: 16,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 15,
    paddingBottom: 10,
  },
  backBtn: {
    width: 40,
    height: 40,
    justifyContent: 'center',
    alignItems: 'center',
  },
  backText: {
    color: '#fff',
    fontSize: 24,
  },
  headerTitle: {
    color: '#fff',
    fontSize: 18,
    fontWeight: '600',
  },
  placeholder: {
    width: 40,
  },
  scrollView: {
    flex: 1,
  },
  imageWrapper: {
    width: SCREEN_WIDTH,
    height: SCREEN_WIDTH,
    backgroundColor: '#fff',
  },
  coverImage: {
    width: '100%',
    height: '100%',
  },
  infoSection: {
    padding: 15,
    marginHorizontal: 10,
    marginTop: 10,
    borderRadius: 12,
    overflow: 'hidden',
  },
  priceRow: {
    flexDirection: 'row',
    alignItems: 'baseline',
  },
  currency: {
    color: '#ff6b00',
    fontSize: 14,
  },
  price: {
    color: '#ff6b00',
    fontSize: 28,
    fontWeight: 'bold',
  },
  presellTag: {
    backgroundColor: '#8b3dff',
    borderRadius: 12,
    paddingHorizontal: 10,
    paddingVertical: 3,
    marginLeft: 10,
  },
  presellText: {
    color: '#fff',
    fontSize: 12,
  },
  name: {
    color: '#333',
    fontSize: 16,
    marginTop: 10,
    lineHeight: 22,
  },
  detailSection: {
    marginTop: 10,
    marginHorizontal: 10,
    padding: 15,
    borderRadius: 12,
    overflow: 'hidden',
  },
  sectionTitle: {
    color: '#333',
    fontSize: 16,
    fontWeight: '600',
    marginBottom: 15,
  },
  detailImage: {
    width: SCREEN_WIDTH - 50,
    height: 300,
    marginBottom: 10,
  },
  recommendSection: {
    marginTop: 10,
    marginHorizontal: 10,
    padding: 15,
    borderRadius: 12,
    overflow: 'hidden',
  },
  recommendItem: {
    width: 120,
    marginRight: 10,
  },
  recommendImage: {
    width: 120,
    height: 120,
    borderRadius: 8,
    backgroundColor: '#fff',
  },
  recommendName: {
    color: '#333',
    fontSize: 12,
    marginTop: 8,
  },
  recommendPrice: {
    color: '#ff6b00',
    fontSize: 14,
    fontWeight: '600',
    marginTop: 4,
  },
  bottomSpace: {
    height: 100,
  },
  bottomBar: {
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 15,
    paddingTop: 10,
    backgroundColor: 'rgba(0,0,0,0.3)',
  },
  serviceBtn: {
    paddingHorizontal: 25,
    paddingVertical: 12,
    backgroundColor: 'rgba(255,255,255,0.9)',
    borderRadius: 25,
  },
  serviceBtnText: {
    color: '#333',
    fontSize: 14,
  },
  buyBtn: {
    flex: 1,
    marginLeft: 15,
    height: 45,
    overflow: 'hidden',
  },
  buyBtnBg: {
    width: '100%',
    height: '100%',
    justifyContent: 'center',
    alignItems: 'center',
  },
  buyBtnText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: '600',
  },
});
